import { useContext, useEffect } from 'react'
import api from '../api'
import { AppContext } from './storeProvider'
import { Actions } from './reducer'
import { DEFAULT_ITEMS_PER_PAGE } from '../components/cardlist/pagination'

export const useGetAllProducts = () => {
	const { state, dispatch } = useContext(AppContext)

	useEffect(() => {
		api
			.getAllProducts()
			.then(({ products }) => {
				dispatch({ type: Actions.SET_ALL_DATA, allData: products })
				dispatch({ type: Actions.SET_PENDING, pending: false })
			})
			.catch((err) => console.log(err))
	}, [state.search, state.pagination.selectedPage, dispatch])
}

export const useGetProduct = () => {
	const { state, dispatch } = useContext(AppContext)

	useEffect(() => {
		api
			.getProducts(
				state.pagination.selectedPage,
				DEFAULT_ITEMS_PER_PAGE,
				state.search
			)
			.then(({ total, products }) => {
				dispatch({
					type: Actions.SET_MAX_PAGE,
					maxPage: Math.ceil(total / DEFAULT_ITEMS_PER_PAGE),
				})
				dispatch({ type: Actions.SET_CATALOG_DATA, catalogData: products })
				dispatch({ type: Actions.SET_PENDING, pending: false })
			})
			.catch((err) => console.log(err))
	}, [state.search, state.pagination.selectedPage, dispatch])
}
